<!-- src/components/PublishArticleModal.vue -->
<template>
  <el-dialog
    title="发布文章"
    v-model="visible"
    @close="handleClose"
    :width="dialogWidth"
    :fullscreen="isMobile"
  >
    <el-form :model="articleForm" :rules="rules" ref="articleFormRef" label-width="100px" :label-position="formLabelPosition">
      <!-- 标题输入 -->
      <el-form-item label="标题" prop="title">
        <el-input v-model="articleForm.title"></el-input>
      </el-form-item>
      
      <!-- 类型输入 -->
      <el-form-item label="类型" prop="type">
        <el-input v-model="articleForm.type"></el-input>
      </el-form-item>
      
      <!-- 关键词输入 -->
      <el-form-item label="关键词" prop="keywords">
        <el-input v-model="articleForm.keywords"></el-input>
      </el-form-item>
      
      <!-- 摘要输入 -->
      <el-form-item label="摘要" prop="summary">
        <el-input type="textarea" v-model="articleForm.summary"></el-input>
      </el-form-item>
      
      <!-- 内容类型选择 -->
      <el-form-item label="内容类型" prop="contentType">
        <el-radio-group v-model="articleForm.contentType">
          <el-radio label="markdown">Markdown</el-radio>
          <el-radio label="richtext">富文本</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <!-- 内容编辑器 -->
      <el-form-item label="内容" prop="content">
        <!-- Markdown 编辑器 -->
        <MarkdownEditor
          v-if="articleForm.contentType === 'markdown'"
          v-model="articleForm.content"
        />
        <!-- 富文本编辑器 -->
        <editor
          v-else
          v-model="articleForm.content"
          :api-key="tinymceApiKey"
          :init="tinymceInit"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handlePublish">发布</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, defineProps, defineEmits, toRefs, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { addArticle } from '@/api/articles'
import MarkdownEditor from './MarkdownEditor.vue'
import Editor from '@tinymce/tinymce-vue'

// 定义组件的 props
const props = defineProps({
  visible: Boolean, // 控制模态框显示/隐藏的 prop
})

// 将 props 转换为响应式引用
const { visible } = toRefs(props)

// 定义组件可以触发的事件
const emit = defineEmits(['close', 'publish-success'])

// 表单引用，用于表单验证
const articleFormRef = ref(null)

// 是否为移动设备
const isMobile = ref(false)

// 文章表单数据
const articleForm = reactive({
  title: '',
  type: '',
  keywords: '',
  summary: '',
  content: '',
  contentType: 'markdown',
  images: [],
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  type: [{ required: true, message: '请输入类型', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
}

// 计算属性：对话框宽度
const dialogWidth = computed(() => isMobile.value ? '100%' : '70%')

// 计算属性：表单标签位置
const formLabelPosition = computed(() => isMobile.value ? 'top' : 'right')

// TinyMCE 编辑器配置
const tinymceApiKey = 'your-tinymce-api-key' // 替换为您的 TinyMCE API 密钥
const tinymceInit = {
  height: 500,
  menubar: false,
  plugins: [
    'advlist autolink lists link image charmap print preview anchor',
    'searchreplace visualblocks code fullscreen',
    'insertdatetime media table paste code help wordcount',
  ],
  toolbar: 'undo redo | formatselect | bold italic backcolor | \
    alignleft aligncenter alignright alignjustify | \
    bullist numlist outdent indent | removeformat | help',
}

// 检查是否为移动设备
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

// 组件挂载时添加窗口大小变化监听
onMounted(() => {
  checkMobile()
  window.addEventListener('resize', checkMobile)
})

// 组件卸载时移除窗口大小变化监听
onUnmounted(() => {
  window.removeEventListener('resize', checkMobile)
})

// 监听 visible prop 的变化
watch(visible, (newValue) => {
  if (newValue) {
    // 模态框打开时的操作
    console.log('模态框已打开')
    resetForm() // 重置表单
  } else {
    // 模态框关闭时的操作
    console.log('模态框已关闭')
  }
})

// 处理关闭模态框
const handleClose = () => {
  emit('close')
  resetForm()
}

// 处理发布文章
const handlePublish = async () => {
  if (!articleFormRef.value) return
  
  await articleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await addArticle(articleForm)
        ElMessage.success('文章发布成功')
        emit('publish-success')
        resetForm()
      } catch (error) {
        ElMessage.error('发布失败：' + error.message)
      }
    } else {
      ElMessage.error('请填写所有必填字段')
    }
  })
}

// 重置表单
const resetForm = () => {
  if (articleFormRef.value) {
    articleFormRef.value.resetFields()
  }
  Object.assign(articleForm, {
    title: '',
    type: '',
    keywords: '',
    summary: '',
    content: '',
    contentType: 'markdown',
    images: [],
  })
}
</script>

<style scoped>
.el-dialog__wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-dialog {
  margin: 0 !important;
}

@media (max-width: 768px) {
  .el-form-item {
    margin-bottom: 15px;
  }
}
</style>